<?php
declare (strict_types = 1);

namespace app\xapply\controller;

use think\facade\Db;
use think\facade\Config;
use think\facade\Cache;

class Uninstall
{
    /**
     * 接口卸载
     */
    public function index()
    {
        $prefix = Config::get('database.connections.mysql.prefix');
        $tables = [
            '__PREFIX__xapply_app',
            '__PREFIX__xapply_category',
            '__PREFIX__xapply_login',
            '__PREFIX__xapply_message',
            '__PREFIX__xapply_rule'
        ];
        $lock = app_path().'install/install.lock';
        if (file_exists($lock)){
            return '如需卸载，请删除'.$lock;
        }
        Db::startTrans();
        try {
            // 删除表
            foreach ($tables as $table){
                $table = str_replace('__PREFIX__', $prefix, $table);
                Db::execute('DROP TABLE IF EXISTS `'.$table.'`');
            }
            // 删除功能模块
            Db::name('AdminModule')->where('name', 'xapply')->delete();
            // 删除功能节点
            Db::name('AdminRule')->where('module', 'xapply')->delete();
            // 删除配置
            Db::name('config')->where('name', 'xapply')->delete();
            $config_view_file = root_path().'app/home/view/conf/xapply.html';
            if (file_exists($config_view_file)){
                unlink($config_view_file);
            }
            $pub = public_path().'static/xapply/';
            $wgt_file = $pub.'__UNI__5FDB086.wgt';
            if (file_exists($wgt_file)){
                unlink($wgt_file);
            }
            if (is_dir($pub)){
                rmdir($pub);
            }
            Cache::clear();
            // 提交事务
            Db::commit();
            $message = '卸载成功';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $message = '卸载失败: '.$e->getMessage();
        }
        return $message;
    }
}
